package com.zzzyh.forumsystemclient.cotroller;

import com.zzzyh.forumsystemclient.common.AppResult;
import com.zzzyh.forumsystemclient.services.IMailService;
import com.zzzyh.forumsystemclient.services.IVerificationCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
@Slf4j
public class EmailController {
    @Autowired
    private IMailService mailService;

    @Autowired
    private IVerificationCodeService verificationCodeService;

    @GetMapping("/sendEmailCode")
    public AppResult<String> sendEmailCode(@RequestParam("email") String email) {
        log.info("收到发送验证码请求，邮箱: {}", email);

        try {
            // 1. 生成验证码
            String code = verificationCodeService.generateCode();
            log.info("生成验证码: {}", code);

            // 2. 保存验证码
            verificationCodeService.saveCode(email, code);

            // 3. 发送邮件
            mailService.sendCodeEmail(email, code);

            return AppResult.success("验证码发送成功，请查收邮件");
        } catch (Exception e) {
            log.error("发送验证码失败，邮箱: {}", email, e);
            return AppResult.failed("验证码发送失败: " + e.getMessage());
        }
    }
}
